package com.ly.blog2backup.controller;

import com.alibaba.fastjson.JSONObject;
import com.ly.blog2Common.core.http.ResponseMessage;
import com.ly.blog2Common.utils.FileUtils;
import com.ly.blog2Common.utils.IOUtils;
import com.ly.blog2backup.config.BackupDataSourceProperties;
import com.ly.blog2backup.constants.BackupConstants;
import com.ly.blog2backup.constants.FileConstants;
import com.ly.blog2backup.service.FileService;
import com.ly.blog2backup.service.MysqlBackupService;
import com.ly.blog2backup.service.impl.FileServiceImpl;
import com.ly.blog2backup.utils.ImageFileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 系统文件处理
 * @author Louis
 * @date Jan 15, 2019
 */
@Controller
@RequestMapping("/file")
public class FileController {

	@Autowired
	private FileService fileService;

	/**
	 * 上传 Base64 编码图片
	 * @return
	 */
	@ResponseBody
	@PostMapping("/uploadBase64")
//	public JSONObject uploadBase64(@RequestBody JSONObject imgBase64Obj) {
	public JSONObject uploadBase64(@RequestParam String imgBase64,@RequestParam String backupBaseUrl) {
//		String imgBase64 = imgBase64Obj.getString("imgBase64");
		//初始化 远程服务器地址
		ImageFileUtils.HTTP = backupBaseUrl + FileConstants.URL;
		return ResponseMessage.ok(fileService.uploadBase64(imgBase64));
	}

	@GetMapping("/readImage/{imageName}")
	public void readImage(@PathVariable("imageName") String imageName,
						  HttpServletRequest request,
						  HttpServletResponse response) {
		ServletOutputStream out = null;
		try {
			BufferedImage image = ImageIO.read(new File(FileConstants.ARTICLE_FOLDER+imageName));
			out = response.getOutputStream();
			ImageIO.write(image, "jpg", out);
			IOUtils.closeQuietly(out);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
